package com.xzcs.shiro;

import com.xzcs.util.web.RequestUtils;
import com.xzcs.util.web.ResponseUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chang
 * @date 2016-12-29 13:44
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        // 清除SavedRequest
        WebUtils.getAndClearSavedRequest(request);
        WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if(this.isLoginRequest(request, response)) {
            if(this.isLoginSubmission(request, response)) {
                return this.executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            if (RequestUtils.isAjaxRequest((HttpServletRequest)request)) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("result", "0");
                map.put("msg", "您尚未登录或登录超时,请重新登录!");
                ResponseUtils.writeJson(map, (HttpServletResponse)response);
            } else {
                this.saveRequestAndRedirectToLogin(request, response);
            }
            return false;
        }
    }
}
